//
//  SinaAuthorizeView.m
//  MrWrite
//
//  Created by lilg on 13-7-25.
//  Copyright (c) 2013年 Founder. All rights reserved.
//

#import "SinaAuthorizeView.h"
#import "SinaWeiBoAPI.h"
#import "ASIFormDataRequest.h"
#import "JSONKit.h"

@implementation SinaAuthorizeView
@synthesize delegate;

-(id)initWithFrame:(CGRect)frame andAppKey:(NSString *)appkey andAppSecret:(NSString *)appSecret andRedirectURI:(NSString *)redirectURI  delegate:(id<SinaAuthorizeDelegate>)sinaAuthorizeDelegate;
{
    self = [super initWithFrame:frame];
    if (self) {
        _appKey = appkey;
        _appSecret = appSecret;
        _redirectURI = redirectURI;
        self.delegate = sinaAuthorizeDelegate;
        UINavigationBar *navagationBar = [[UINavigationBar alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, NavagationBarHeight)];
        [navagationBar setBarStyle:UIBarStyleBlack];
        [self addSubview:navagationBar];
        [navagationBar release];

        UILabel  *shareNaeLab = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, NavagationBarHeight)];
        shareNaeLab.backgroundColor = [UIColor clearColor];
        [shareNaeLab setText:@"新浪微博分享"];
        [shareNaeLab setTextAlignment:NSTextAlignmentCenter];
        [shareNaeLab setFont:[UIFont boldSystemFontOfSize:20]];
        [shareNaeLab setTextColor:[UIColor whiteColor]];
        [self addSubview:shareNaeLab];

        UIButton  *CancelButton = [[UIButton alloc]initWithFrame:CGRectMake(15, 10, 12, 22)];
        [CancelButton addTarget:self action:@selector(HideWebView) forControlEvents:UIControlEventTouchUpInside];
        [CancelButton setImage:[UIImage imageNamed:@"setting_back"] forState:UIControlStateNormal];
        [self addSubview:CancelButton];
        [CancelButton release];

        UIWebView *loginWebView = [[UIWebView alloc]initWithFrame:CGRectMake(0, NavagationBarHeight, SCREENWIDTH, SCREENHEIGHT-NavagationBarHeight)];
        loginWebView.delegate =self;
        NSString *strurl = SinaWeiBoOauth2(SINA_App_Key,RedirectURL);
        NSURL *urls = [NSURL URLWithString:strurl];
        NSURLRequest *request = [[NSURLRequest alloc] initWithURL:urls];
        [loginWebView loadRequest:request];
        [request release];
        [self addSubview:loginWebView];
        [loginWebView release];
    }
    return self;
}

- (void)HideWebView
{
    CGRect __block frame = self.frame;
    [UIView animateWithDuration:0.3 animations:^{
      self.frame = frame;
      frame = self.frame;
      frame.origin.y = 460;
      self.frame = frame;
    } completion:^(BOOL finished)
    {
        if ([delegate respondsToSelector:@selector(sinaAuthorizeDelegateCancel)]) {
            [delegate sinaAuthorizeDelegateCancel];
        }
      [self removeFromSuperview];
    }];
}

- (void)ShowWebView
{
  UIWindow *window = [UIApplication sharedApplication].keyWindow;
	if (!window)
  {
		window = [[UIApplication sharedApplication].windows objectAtIndex:0];
	}
    CGRect __block frame = self.frame;
    frame.origin.y = SCREEN_HEIGHT;
    self.frame = frame;
    [window addSubview:self];
    [UIView animateWithDuration:0.3 animations:^{
      frame = self.frame;
      frame.origin.x = 0;
      frame.origin.y = 20;
      self.frame = frame;
    } completion:^(BOOL finished) {
      
    }];
  
}


#pragma Mark -WebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
  NSString *requestString = [[request URL] absoluteString];
  NSString *holdstr = [NSString stringWithFormat:@"%@?code=",_redirectURI];
  NSRange range = [requestString rangeOfString:holdstr];
  if (range.length!=0)
  {
    NSString *code = [NSString stringWithFormat:@"%@",[requestString substringFromIndex:range.length]];
    NSString *requestTokenStr = SinaAccessToken(_appKey, _appSecret, _redirectURI, code);
    NSURL *requestTokenURL = [NSURL URLWithString:[requestTokenStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    ASIHTTPRequest *tokenRequest = [ASIHTTPRequest requestWithURL:requestTokenURL];
    [tokenRequest setRequestMethod:@"POST"];
    [tokenRequest setValidatesSecureCertificate:YES];
    [tokenRequest startSynchronous];
    NSError *error = [tokenRequest error];
    if (error)
    {
      NSLog(@"SinaOauth  ERR %@",error);
      UIAlertView *action = [[UIAlertView alloc] initWithTitle:@"错误" message:@"授权失败，请重试。" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
      [action show];
      [action release];
      [self HideWebView];
      return  NO;
    }
    NSString * response = [[NSString alloc] initWithData:[tokenRequest responseData] encoding:NSUTF8StringEncoding];
      NSData* jsonData = [response dataUsingEncoding:NSUTF8StringEncoding];
      NSDictionary *responseDic = [jsonData objectFromJSONData];
    if ([self.delegate respondsToSelector:@selector(sinaAuthorizeDelegateDidLogin:)]) {
      [delegate sinaAuthorizeDelegateDidLogin:responseDic];
      [self HideWebView];
    }
    [response release];
  }
  return YES;
}
@end
